package com.qf.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.qf.config.ServerConfig;
import com.qf.fallback.CustomerFallback;
import com.qf.feign.CustomerFeign;
import com.qf.feign.ProviderFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lixu
 */
@RestController
@RequestMapping(ServerConfig.CUSTOMER)
@RefreshScope//不停机维护
public class CustomerController implements CustomerFeign {

    @Autowired
    private ProviderFeign providerFeign;
    @Autowired //Tomcat 加载SpringIOC
    private RedisTemplate redisTemplate;//RedisTemplate没有重新去加载 application.yml

    @Value("${version}")
    private String version;
    /**
     * 消费者  资源名就是路径 /customer/list
     *        blockHandler:抛出是 BlockException异常的时候
     *
     *      1。流控  被控制了就blockHandler方法进行降级处理   是限流
     *      2
     *
     *
     *      String 热点数据： 有值 代表香车    0角标 索引是0
     *      String 不算热点数据： 有值 代表香车    1角标 索引是1
     *
     * @return
     */
    @Override
    @SentinelResource(value = "xxx",fallback = "fallbackList",blockHandler = "blockHandlerList",
      fallbackClass = {CustomerFallback.class}//,
    //exceptionsToIgnore = {ArithmeticException.class}
    )//忽略此异常 不进行fallback
    public String list(Integer id) {//Id就是0


        if(id == 123){
            //100%失败
            int i = 1/0;//抛出算术异常 ArithmeticException.class 不执行降级处理fallback
        }

        //保存
        ///redisTemplate.opsForValue().set("qf","8888888");
        return "我是消费者:" + version;
        //return "我是消费者：我要调用：" + providerFeign.list();
    }


    /**
     * 关联
     * @return
     */
    @GetMapping("/a")
    public String a(){

        return "我是a";
    }


    /**
     *  降级处理的方法
     * @param id
     * @param throwable
     * @return
     */
/*    public String fallbackList(Integer id,Throwable throwable) {
        System.out.println(throwable.getMessage());
        return "我是消费者的Sentinel降级方法fallbackList";
    }*/

    /**
     * 流控 处理方案
     * @param be
     * @return
     */
    public String blockHandlerList(BlockException be) {
        System.out.println(be.getMessage());
        return "我是消费者的Sentinel降级方法blockHandlerList";
    }
}
